<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="120px"
    @submit.prevent="handleSubmit"
  >
    <el-form-item label="项目名称" prop="projectName">
      <el-input v-model="form.projectName" placeholder="请输入项目名称" />
    </el-form-item>
    
    <el-form-item label="Gitee仓库地址" prop="repoUrl">
      <el-input v-model="form.repoUrl" placeholder="https://gitee.com/username/repository.git" />
    </el-form-item>
    
    <el-form-item label="分支" prop="branch">
      <el-input v-model="form.branch" placeholder="main" />
    </el-form-item>
    
    <el-form-item label="部署路径" prop="deployPath">
      <el-input v-model="form.deployPath" placeholder="本地部署：./deployments/project 或 远程部署：/var/www/project" />
      <div class="form-tip">
        <el-text size="small" type="info">
          本地部署：使用相对路径，如 ./deployments/project<br>
          远程部署：使用绝对路径，如 /var/www/project
        </el-text>
      </div>
    </el-form-item>
    
    <el-form-item label="构建命令" prop="buildCommand">
      <el-input v-model="form.buildCommand" placeholder="npm run build" />
    </el-form-item>
    
    <el-form-item label="部署前命令" prop="preDeployCommand">
      <el-input v-model="form.preDeployCommand" placeholder="可选，如：npm install" />
    </el-form-item>
    
    <el-form-item label="部署后命令" prop="postDeployCommand">
      <el-input v-model="form.postDeployCommand" placeholder="可选，如：pm2 restart" />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        {{ props.isEdit ? '更新部署' : '创建部署' }}
      </el-button>
      <el-button @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useDeploymentStore } from '@/stores/deployment'

interface Props {
  deployment?: any
  isEdit?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  deployment: undefined,
  isEdit: false
})

const emit = defineEmits<{
  close: []
  success: []
}>()

const deploymentStore = useDeploymentStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

const form = reactive({
  projectName: '',
  repoUrl: '',
  branch: 'main',
  deployPath: '',
  buildCommand: 'npm run build',
  preDeployCommand: '',
  postDeployCommand: ''
})

// 填充表单数据的函数
const fillFormData = () => {
  console.log('fillFormData called:', { isEdit: props.isEdit, deployment: props.deployment })
  if (props.isEdit && props.deployment) {
    const formData = {
      projectName: props.deployment.projectName,
      repoUrl: props.deployment.repoUrl,
      branch: props.deployment.branch,
      deployPath: props.deployment.deployPath,
      buildCommand: props.deployment.buildCommand,
      preDeployCommand: props.deployment.preDeployCommand || '',
      postDeployCommand: props.deployment.postDeployCommand || ''
    }
    console.log('Filling form with:', formData)
    Object.assign(form, formData)
  }
}

// 监听 props 变化，重新填充表单数据
watch(() => props.deployment, () => {
  fillFormData()
}, { immediate: true, deep: true })

// 监听编辑模式变化
watch(() => props.isEdit, () => {
  fillFormData()
}, { immediate: true })

const rules: FormRules = {
  projectName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  repoUrl: [
    { required: true, message: '请输入仓库地址', trigger: 'blur' },
    { pattern: /^https:\/\/gitee\.com\/.+\.git$/, message: '请输入正确的Gitee仓库地址', trigger: 'blur' }
  ],
  branch: [
    { required: true, message: '请输入分支名称', trigger: 'blur' }
  ],
  deployPath: [
    { required: true, message: '请输入部署路径', trigger: 'blur' }
  ],
  buildCommand: [
    { required: true, message: '请输入构建命令', trigger: 'blur' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (props.isEdit && props.deployment) {
      await deploymentStore.updateDeployment(props.deployment.id, form)
      ElMessage.success('部署配置更新成功')
    } else {
      await deploymentStore.createDeployment(form)
      ElMessage.success('部署配置创建成功')
    }
    
    emit('success')
  } catch (error) {
    if (error !== false) {
      ElMessage.error(props.isEdit ? '更新失败' : '创建失败')
    }
  } finally {
    loading.value = false
  }
}
</script>
